package com.cskaoyan.gateway.controller.user;

import com.alibaba.fastjson.JSON;
import com.mall.commons.result.ResponseData;
import com.mall.commons.result.ResponseUtil;
import com.mall.commons.tool.utils.CookieUtil;
import com.mall.user.IKaptchaService;
import com.mall.user.ILoginService;
import com.mall.user.annotation.Anoymous;
import com.mall.user.constants.SysRetCodeConstants;
import com.mall.user.dto.*;
import com.mall.user.intercepter.TokenIntercepter;
import lombok.extern.slf4j.Slf4j;
import org.apache.dubbo.config.annotation.Reference;
import org.springframework.web.bind.annotation.*;

import javax.servlet.http.Cookie;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.net.InetAddress;
import java.net.UnknownHostException;
import java.util.Map;

@RestController
@RequestMapping("/user")
@Slf4j
public class LoginController {

    @Reference(timeout = 5000,check = false)
    IKaptchaService iKaptchaService;

    @Reference(timeout = 5000,check = false)
    ILoginService loginService;


    @PostMapping
    @RequestMapping("/login")
    @Anoymous
    public ResponseData login(@RequestBody Map<String, String> map, HttpServletRequest request, HttpServletResponse response) {
        // 验证校验码
        KaptchaCodeResponse kaptchaCodeResponse = verifyCaptchaCode(map, request);
        if (!SysRetCodeConstants.SUCCESS.getCode().equals(kaptchaCodeResponse.getCode())) {
            return new ResponseUtil<>().setErrorMsg(kaptchaCodeResponse.getMsg());
        }


        UserLoginRequest userLoginRequest = new UserLoginRequest();
        userLoginRequest.setUserName(map.get("userName"));
        userLoginRequest.setPassword(map.get("userPwd"));

        UserLoginResponse login = loginService.login(userLoginRequest);
        if (!SysRetCodeConstants.SUCCESS.getCode().equals(login.getCode())) {
            return new ResponseUtil<>().setErrorMsg(login.getMsg());
        }

        // 将token作为cookie写回到浏览器
        addCookie(response, login);

        return new ResponseUtil<>().setData(login);

    }

    private void addCookie(HttpServletResponse response, UserLoginResponse login) {
        // # issue1 在这里写回cookie 的时候用的是
        // CookieUtil.genCookieWithDomain(TokenIntercepter.ACCESS_TOKEN, login.getToken(), 60 * 60 * 24, hostAddress)
        Cookie tokenCookie = CookieUtil.genCookie(TokenIntercepter.ACCESS_TOKEN, login.getToken(), "/",60 * 60 * 24);
        log.info("cookie domain is " + tokenCookie.getDomain());
        response.addCookie(tokenCookie);
    }

    /*
        验证用户输入的验证码
    */
    private KaptchaCodeResponse verifyCaptchaCode(Map<String, String> map, HttpServletRequest request) {
        // 获取用户输入的校验码
        String captcha = map.get("captcha");
        KaptchaCodeRequest kaptchaCodeRequest = new KaptchaCodeRequest();

        String uuid = CookieUtil.getCookieValue(request, "kaptcha_uuid");
        kaptchaCodeRequest.setUuid(uuid);
        kaptchaCodeRequest.setCode(captcha);

        return iKaptchaService.validateKaptchaCode(kaptchaCodeRequest);
    }

    @GetMapping("/loginOut")
    public ResponseData logout(HttpServletRequest request, HttpServletResponse response) {

        // 在浏览器中删除token
        deleteCookie(response, request);
        return new ResponseUtil().setData(null);
    }

    private void deleteCookie(HttpServletResponse response, HttpServletRequest request) {
        //获取到 id
        //Cookie cookieToken = CookieUtil.genCookie(TokenIntercepter.ACCESS_TOKEN, "", "/", 0);

        Cookie[] cookies = request.getCookies();
        if (null!=cookies) {
            for(Cookie cookie : cookies){
                if(cookie.getName().equals(TokenIntercepter.ACCESS_TOKEN)){
                    cookie.setValue(null);
                    cookie.setMaxAge(0);// 立即销毁cookie
                    cookie.setPath("/");
                    log.info("deleted cookie domain is: " + cookie.getDomain());
                    response.addCookie(cookie); //覆盖原来的token
                }
            }
        }
    }

    @GetMapping("/login")
    public ResponseData checkLogin(HttpServletRequest request) {
        // 从cookie里面去取token
        String token = (String) request.getAttribute(TokenIntercepter.USER_INFO_KEY);
        log.info("checkLogin token  responseData: " + token);
        Object userInfoObj = JSON.parse(token);

        return new ResponseUtil().setData(userInfoObj);
    }





}
